<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="resetForm"
        @reset="searchSubmit"
      >
        <Button style="display: inline-block;margin-right:10px;" @click="handleCheck">检查</Button>
        <Button
          style="display: inline-block;"
          @click="handleExport"
          >导出</Button
        >
      </FilterForm>
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer
        style="
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <!-- <div style="display: flex; margin: 0">
          <Button style="margin-right: 12px" @click="actionUnfoldFunc(true)"
            >展开所有节点</Button
          >
          <Button
            type="info"
            style="color: #217dfa; border: 1px solid #217dfa"
            @click="actionUnfoldFunc(false)"
            >折叠所有节点</Button
          >
        </div> -->
      </OperationContainer>
      <el-table
        ref="ctab"
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
        row-key="accountcode"
        height="100%"
        :tree-props="{ children: 'childrenList', hasChildren: 'hasChildren' }"
        :default-expand-all="isExpand"
      >
        <el-table-column align="center" type="index" label="" width="60" />
        <el-table-column prop="accountcode" label="会计科目代码" width="120" />
        <el-table-column prop="accountname" label="会计科目名称" />
        <el-table-column prop="deptCode" label="费用要素编码" width="120" />
        <el-table-column prop="deptName" label="费用要素名称" />
        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="scope">
            <i
              v-if="scope.row.isend == 1"
              class="el-icon-edit-outline"
              style="
                padding-top: 4px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleEdit(scope.row)"
            />
            <i
              v-if="scope.row.isend == 1"
              class="el-icon-delete"
              style="
                padding-top: 4px;
                padding-left: 10px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="deleteDetail(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <Dialog
        title="编辑"
        :visible="dialogVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="dialogVisible = false"
        @confirm="dialogConfirm"
      >
        <div class="form-box" style="margin-top: 20px">
          <div class="form-item">
            <span class="require">会计科目名称</span>
            <el-select
              v-model="currentItem.edExtraFirstCode"
              style="width: 60%"
              clearable
              placeholder="会计科目名称"
              size="mini"
              disabled
            >
              <el-option
                v-for="(item, index) in kjDeptList"
                :key="index"
                :label="item.accountname"
                :value="item.accountcode"
              />
            </el-select>
          </div>
        </div>
        <div class="form-box">
          <div class="form-item">
            <span class="require">费用要素</span>
            <el-select
              v-model="currentItem.edExtraSecondCode"
              style="width: 60%"
              clearable
              placeholder="请选择费用要素"
              size="mini"
              filterable
            >
              <el-option
                v-for="(item, index) in costItemList"
                :key="index"
                :label="`${item.edCode}-${item.edName}`"
                :value="item.edCode"
              />
            </el-select>
          </div>
        </div>
      </Dialog>
      <Dialog
        title="提示"
        :visible="tableDialog"
        :footer-btns="[
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="tableDialog = false"
      >
        <el-table
          v-loading="isDialog"
          :data="tableDataDialog"
          border
          :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
          header-row-class-name="ck-table-header"
          row-class-name="ck-table-row"
          size="small"
          height="40vh"
          style="width: 450px"
        >
          <el-table-column align="center" type="index" label="" width="60" />
          <el-table-column
            prop="accountcode"
            label="会计科目代码"
            width="120"
          />
          <el-table-column prop="accountname" label="会计科目名称" />
        </el-table>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import {
  getAccountOrgationSource,
  getAccountSource,
  getCheck,
} from "../../../utils/apis/dataExchange/index";
import {
  getEnumDetailSource,
  modifyEnumDetail,
} from "../../../utils/apis/accountingUnit/factor";
import {
  getEnumDetailSourcePage,
  batchDeleteEnumDetail,
  addEnumDetail,
  getCostOfUfDownLoadExcel
} from "../../../utils/apis/basic";
import { BasicParams } from "../../../utils/basicParams";
import { YySysterm } from "../../../utils/yySysterm";
export default {
  name: "YySyetem", // 成本-用友系统
  components: {},
  data() {
    return {
      tableDataDialog: [],
      tableDialog: false,
      isDialog: false,
      rowId: "",
      filterElements: [
        {
          key: "accountcode",
          type: "Select",
          label: "会计科目名称",
          value: "",
          width: 210,
          itemLabel: "accountname",
          itemValue: "accountcode",
          options: [],
          filterable: true,
          clearable: true,
        },
        {
          key: "iyear",
          label: "年",
          mode: "year",
          type: "date-picker",
          format: "yyyy",
          expiredDate: {},
          value: '',
          width: 340,
        },
        // {
        //   key: "deptCode",
        //   type: "Select",
        //   label: "费用要素",
        //   value: "",
        //   width: 210,
        //   itemLabel: "edName",
        //   itemValue: "edCode",
        //   options: [],
        //   filterable: true,
        //   clearable: true,
        // },
        // {
        //   key: "relationStatus",
        //   type: "Select",
        //   label: "关联状态",
        //   value: "",
        //   width: 210,
        //   filterable: true,
        //   clearable: true,
        //   options: [
        //     {
        //       label: "全部",
        //       value: "",
        //     },
        //     {
        //       label: "已关联",
        //       value: "1",
        //     },
        //     {
        //       label: "未关联",
        //       value: "0",
        //     },
        //   ],
        // },
      ],
      tableData: [],
      tableLoading: false,
      isExpand: true, // 默认为展开状态
      dialogVisible: false,
      currentItem: {
        edExtraFirstDescription: "",
        edExtraFirstCode: "",
        edExtraSecondCode: "",
        edExtraSecondDescription: "",
      },
      costItemList: [],
      kjDeptList: [],
      newTime: "",
      newParamList: {},
    };
  },
  created() {},
  mounted() {
    this.getSelect();
  },
  methods: {
        handleExport(){ //导出
        const param = {
          sysid: 'Cost',
          iyear:this.$refs.filterForm.getParms()?.iyear
        }
    getCostOfUfDownLoadExcel(param).then(res => {
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '成本-用友系统.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    handleCheck(value) {
      let yySysterm = new YySysterm();
      yySysterm.accountcode = this.filterElements[0].value;
      yySysterm.sysid = "Cost";
      yySysterm.relationStatus = 0;
      getCheck(yySysterm).then((res) => {
        if (res.data.code == 200) {
          this.tableDialog = true;
          this.tableDataDialog = res.data.data;
        }
      });
    },
    getData(value) {
      // 获取列表
      let yySysterm = new YySysterm();
      yySysterm.accountcode = value.accountcode;
      yySysterm.iyear = value.iyear
      // yySysterm.relationStatus = value.relationStatus;
      // yySysterm.deptCode = value.deptCode;
      yySysterm.sysid = "Cost";
      this.tableLoading = true;
      getAccountOrgationSource(yySysterm).then((res) => {
        if (res.data.code === 200) {
          this.tableLoading = false;
          this.tableData = res.data.data;
        }
      });
    },
    getSelect() {
      // 会计科目名称
      let yySysterm = new YySysterm();
      yySysterm.sysid = "Cost";
      getAccountSource(yySysterm).then(async (res) => {
        if (res.data.code === 200) {
          this.filterElements[0].options = res.data.data;
          this.kjDeptList = res.data.data;
        }
      });
      // 费用要素
      let basicParams = new BasicParams();
      basicParams.edParentCode = "CostItem";
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          // this.filterElements[1].options = res.data.data;
          this.costItemList = res.data.data;
        }
      });
    },
    resetForm(data) {
      // 查询
      this.newParamList = data;
      this.getData(data);
    },
    selectChange(val) {
      this.currentItem.edExtraSecondCode = val;
      const arr = this.costItemList.filter((item) => {
        return item.value === val;
      });
      this.currentItem.edExtraSecondDescription = arr[0].label;
    },
    dialogConfirm() {
      // 保存
      if (!this.currentItem.edExtraFirstCode) {
        this.$message.warning("请选择会计科目名称");
        return;
      }
      if (!this.currentItem.edExtraSecondCode) {
        this.$message.warning("请选择费用要素");
        return;
      }
      let basicParams = new BasicParams();
      basicParams.edExtraFirstCode = this.currentItem.edExtraFirstCode;
      basicParams.edExtraFirstDescription = this.kjDeptList.find(
        (item) => item.accountcode == this.currentItem.edExtraFirstCode
      ).accountname;
      basicParams.edExtraSecondCode = this.currentItem.edExtraSecondCode;
      basicParams.edExtraSecondDescription = this.costItemList.find(
        (item) => item.edCode == this.currentItem.edExtraSecondCode
      ).edName;
      basicParams.edCode = `${this.currentItem.edExtraFirstCode}-${this.currentItem.edExtraSecondCode}`;
      basicParams.edParentCode = "RD_CostUFIDARelation";
      basicParams.edName = `成本-用友对应`;
      if (this.rowId) {
        //编辑
        basicParams.edId = this.rowId;
        modifyEnumDetail(basicParams).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("编辑成功");
            this.dialogVisible = false;
            this.getData({});
            this.searchSubmit();
          }
        });
      } else {
        //新增

        addEnumDetail(basicParams).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message);
            this.dialogVisible = false;
            this.getData({});
            this.searchSubmit();
          }
        });
      }
    },
    deleteDetail(row) {
      //删除
      let ids = [row.edId];
      this.$confirm({
        title: "温馨提示",
        content: "您确定要删除该条数据?",
        okText: "确定",
        cancelText: "取消",
        okFn: () => {
          batchDeleteEnumDetail(ids).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message);
              this.getData({});
            } else {
              this.$message.error(res.data.message);
            }
          });
        },
        cancelFn: () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        },
      });
    },
    searchSubmit() {}, // 重置
    handleEdit(row) {
      // 编辑
      this.rowId = row.edId;
      this.dialogVisible = true;
      let basicParams = new BasicParams();
      basicParams.edId = row.edId;
      basicParams.edParentCode = "RD_CostUFIDARelation";
      this.currentItem.edExtraFirstCode = "";
      this.currentItem.edExtraSecondCode = "";
      const rows = JSON.parse(JSON.stringify(row))
      this.currentItem.edExtraFirstCode = rows.accountcode;
      this.currentItem.edExtraSecondCode = rows.deptCode;
      // if (row.edId) {
      //   getEnumDetailSource(basicParams).then((res) => {
      //     if (res.data.code === 200) {
      //       this.currentItem.edExtraFirstCode =
      //         res.data.data[0].edExtraFirstCode;
      //       this.currentItem.edExtraSecondCode =
      //         res.data.data[0].edExtraSecondCode;
      //     } else {
      //       this.$message.error(res.data.message);
      //     }
      //   });
      // } else {
      //   this.currentItem.edExtraFirstCode = row.accountcode;
      // }
    },
    actionUnfoldFunc(isAss) {
      // 展开和折叠所有节点
      this.isExpand = isAss;
      this.$nextTick(() => {
        this.forArr(this.tableData, this.isExpand);
      });
    },
    // 遍历
    forArr(arr, isExpand) {
      arr.forEach((i) => {
        // toggleRowExpansion见element文档
        this.$refs.ctab.toggleRowExpansion(i, isExpand);
        if (i.childrenList) {
          this.forArr(i.childrenList, isExpand);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.form-box {
  display: flex;
  margin-bottom: 20px;
}
.form-item {
  align-items: center;
  display: flex;
}

.form-item span {
  width: 110px;
  text-align: right;
  margin-right: 10px;
}

.form-item span::after {
  content: "：";
}
</style>
